package com.ssy.lingxi.purchase.handler.validator;

import com.ssy.lingxi.purchase.handler.annotation.DeliveryMethodAnnotation;
import com.ssy.lingxi.purchase.handler.annotation.DeliveryTypeAnnotation;
import com.ssy.lingxi.purchase.model.enums.DeliveryMethodEnum;
import com.ssy.lingxi.purchase.model.enums.DeliveryTypeEnum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;

/**
 * 直送客户/客户自提参数校验注解校验类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-05-31
 */
public class DeliveryTypeValidator implements ConstraintValidator<DeliveryTypeAnnotation, Integer> {
    private boolean required = true;

    @Override
    public void initialize(DeliveryTypeAnnotation deliveryTypeAnnotation) {
        required = deliveryTypeAnnotation.required();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if(!required) {
            return true;
        }

        if(value == null || "".equals(value) || value <= 0) {
            return false;
        }

        return Arrays.stream(DeliveryTypeEnum.values()).anyMatch(v -> v.getCode().equals(value));
    }
}
